package com.heima;

import cn.hutool.json.JSONUtil;
import com.hmall.item.ItemApplication;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.item.service.IItemService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;


@SpringBootTest(classes = ItemApplication.class)
public class ElasticSearchTest02 {

    private RestHighLevelClient client;

    @Autowired
    private IItemService itemService;


    @Test
    void testMatchAll() throws IOException{

        //准备Request
        SearchRequest request = new SearchRequest("items");

        //设置DSL
        request.source()
                .query(QueryBuilders.matchAllQuery());

        //发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //解析结果
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("总条数:" + total);
        //数据
        SearchHit[] hits = searchHits.getHits();

        for (SearchHit hit : hits) {
            //获取source结果
            String json = hit.getSourceAsString();
            //转换为ItemDoc对象
            ItemDoc itemDoc = JSONUtil.toBean(json, ItemDoc.class);
            System.out.println(itemDoc);
        }
    }


    @BeforeEach
    void setUp(){
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("127.0.0.1:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}